import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:yp/Xwidgets/cache_image.dart';
import 'package:yp/config/config.dart';
import 'package:yp/helper.dart';
import 'package:yp/router.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:sp_util/sp_util.dart';

import 'logic.dart';
import 'state.dart';

class CommoditySearchListPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _CommoditySearchListPage();
  }
}

class _CommoditySearchListPage extends State<CommoditySearchListPage> {
  final CommoditySearchListLogic logic = Get.put(CommoditySearchListLogic());
  final CommoditySearchListState state =
      Get.find<CommoditySearchListLogic>().state;

  @override
  Widget build(BuildContext context) {
    return GetBuilder<CommoditySearchListLogic>(
      builder: (logic) {
        return Scaffold(
          appBar: AppBar(
            centerTitle: true,
            elevation: setWidth(1),
            backgroundColor: Color(0xffe7551e),
            title: Text(
              state.titleString,
              style: TextStyle(
                color: Colors.white,
                fontSize: 17,
              ),
            ),

            iconTheme: IconThemeData(
              color: Colors.white,
            ),
          ),
          body: Container(
            color: Color(0xffF7F7F7),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  color: Colors.white,
                  height: setWidth(90),
                  child: Row(
                    children: [
                      InkWell(
                        onTap: () {
                          if (state.chooseIndex != 0) {
                            logic.chooseSortingClick(0);
                          }
                        },
                        child: Container(
                          width: setWidth(165),
                          height: setWidth(90),
                          alignment: Alignment.center,
                          child: Text(
                            '综合排序',
                            style: TextStyle(
                              color: state.chooseIndex == 0
                                  ? Color(0xffe7551e)
                                  : Color(0xff333333),
                              fontSize: 12,
                            ),
                          ),
                        ),
                      ),
                      InkWell(
                        onTap: () {
                          if (state.chooseIndex != 1) {
                            logic.chooseSortingClick(1);
                          }
                        },
                        child: Container(
                          width: setWidth(165),
                          height: setWidth(90),
                          alignment: Alignment.center,
                          child: Text(
                            '销量排序',
                            style: TextStyle(
                              color: state.chooseIndex == 1
                                  ? Color(0xffe7551e)
                                  : Color(0xff333333),
                              fontSize: 12,
                            ),
                          ),
                        ),
                      ),
                      InkWell(
                        onTap: () {
                          logic.chooseSortingClick(2);
                        },
                        child: Container(
                          width: setWidth(165),
                          height: setWidth(90),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text(
                                '价格排序',
                                style: TextStyle(
                                  color: state.chooseIndex == 2
                                      ? Color(0xffe7551e)
                                      : Color(0xff333333),
                                  fontSize: 12,
                                ),
                              ),
                              SizedBox(
                                width: setWidth(10),
                              ),
                              Image.asset(
                                state.chooseIndex != 2
                                    ? 'assets/images/sort_def.png'
                                    : (state.sortingBool == false
                                        ? 'assets/images/sort_desc.png'
                                        : 'assets/images/sort_asc.png'),
                                width: setWidth(14),
                                height: setWidth(16),
                                fit: BoxFit.cover,
                              ),
                            ],
                          ),
                        ),
                      ),
                      InkWell(
                        onTap: () {
                          if (state.chooseIndex != 3) {
                            logic.chooseSortingClick(3);
                          }
                        },
                        child: Container(
                          width: setWidth(165),
                          height: setWidth(90),
                          alignment: Alignment.center,
                          child: Text(
                            '上新',
                            style: TextStyle(
                              color: state.chooseIndex == 3
                                  ? Color(0xffe7551e)
                                  : Color(0xff333333),
                              fontSize: 12,
                            ),
                          ),
                        ),
                      ),
                      InkWell(
                        onTap: () {
                          print('++++++++++ 切换 单双排 ++++++++++');
                          logic
                              .singleDoubleRowClick(!state.singleDoubleRowBool);
                        },
                        child: Container(
                          width: setWidth(90),
                          height: setWidth(90),
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Container(
                                width: setWidth(2),
                                height: setWidth(30),
                                color: Color(0xffcccccc),
                              ),
                              Container(
                                width: setWidth(88),
                                height: setWidth(90),
                                padding: EdgeInsets.symmetric(
                                    horizontal: setWidth(24),
                                    vertical: setWidth(25)),
                                child: Image.asset(
                                  // 'assets/images/classificationIcon.png',
                                  state.singleDoubleRowBool
                                      ? 'assets/images/classificationIcon.png'
                                      : 'assets/images/singleRow_image.png',
                                  width: setWidth(40),
                                  height: setWidth(40),
                                  fit: BoxFit.cover,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(
                  height:
                      !state.singleDoubleRowBool ? setWidth(20) : setWidth(0),
                ),
                Expanded(
                  child: Container(
                    child: SmartRefresher(
                      controller: state.controller1,
                      header: CustomHeader(
                        builder: (BuildContext context, RefreshStatus mode) {
                          Widget body;
                          if (mode == RefreshStatus.completed) {
                            body = CupertinoActivityIndicator();
                          }
                          return Container(
                            height: 55.0,
                            child: Center(child: body),
                          );
                        },
                      ),
                      footer: CustomFooter(
                        builder: (BuildContext context, LoadStatus mode) {
                          Widget body;
                          if (mode == LoadStatus.idle) {
                            body = Text("没有更多数据了");
                          } else if (mode == LoadStatus.loading) {
                            body = CupertinoActivityIndicator();
                          } else if (mode == LoadStatus.failed) {
                            body = Text("刷新失败");
                          } else {
                            body = Text("没有更多数据了");
                          }
                          return Container(
                            height: 55.0,
                            child: Center(child: body),
                          );
                        },
                      ),
                      enablePullUp: true,
                      enablePullDown: true,
                      onRefresh: logic.refreshData,
                      onLoading: logic.loadMoreData,
                      child: !state.singleDoubleRowBool
                          ? StaggeredGridView.countBuilder(
                              shrinkWrap: true,
                              padding: EdgeInsets.symmetric(
                                  horizontal: setWidth(26)),
                              crossAxisCount: 4,
                              itemCount: state.goodsList.length,
                              itemBuilder: (BuildContext context, int index) {
                                return _doubleRowItemWidget(index: index);
                              },
                              staggeredTileBuilder: (index) =>
                                  StaggeredTile.fit(2),
                              mainAxisSpacing: setWidth(20), // 排间距
                              crossAxisSpacing: setWidth(18), // 列间距
                            )
                          : ListView.builder(
                              itemBuilder: (context, index) {
                                return _singleRowItemWidget(index: index);
                              },
                              itemCount: state.goodsList.length,
                            ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  // 双排 item
  Widget _doubleRowItemWidget({
    int index,
  }) {
    String priceStr = '', oldPriceStr = '', tiShi = '';
    bool oldBool = false;
    if (state.goodsList[index]['is_seckill'] == 1) {
      // 秒杀商品
      priceStr = state.goodsList[index]['price'].toString();
      oldBool = state.goodsList[index]['mkt_price'] >
          state.goodsList[index]['price']; // 显示旧价格
      oldPriceStr = state.goodsList[index]['mkt_price'].toString();
    } else if (state.goodsList[index]['is_pre_sale'] == 1) {
      priceStr = state.goodsList[index]['price'].toString();
      oldBool = state.goodsList[index]['mkt_price'] >
          state.goodsList[index]['price']; // 显示旧价格
      oldPriceStr = state.goodsList[index]['mkt_price'].toString();
    } else {
      if (state.goodsList[index]['expect_price'] > 0) {
        priceStr = '${state.goodsList[index]['expect_price'].toString()}';
        tiShi = '折后';
        oldBool = state.goodsList[index]['mkt_price'] >
            state.goodsList[index]['expect_price']; // 显示旧价格
        oldPriceStr = state.goodsList[index]['mkt_price'].toString();
      } else {
        priceStr = state.goodsList[index]['price'].toString();
        oldBool = state.goodsList[index]['mkt_price'] >
            state.goodsList[index]['price']; // 显示旧价格
        oldPriceStr = state.goodsList[index]['mkt_price'].toString();
      }
    }
    bool soldOutBool = state.goodsList[index]['style_store'] <= 0;

    return InkWell(
      onTap: () {
        String itemNumId =
            state.goodsList[index]['default_item_num_id']?.toString() ?? '';
        String styleNumId =
            state.goodsList[index]['style_num_id']?.toString() ?? '';
        String shopId = state.goodsList[index]['shop_num_id']?.toString() ?? '';
        Get.toNamed(RouteConfig.goodsDetail, arguments: {
          'itemNumId': itemNumId,
          'styleNumId': styleNumId,
          'shopId': shopId,
          'typeIndex': state.goodsList[index]['is_pre_sale'],
        });
      },
      child: Container(
        color: Colors.white,
        width: setWidth(340),
        height: setWidth(530),
        padding: EdgeInsets.only(
          left: setWidth(20),
          top: setWidth(26),
          right: setWidth(20),
          // bottom: setWidth(46),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Stack(
              children: [
                CachedImage(
                  width: setWidth(300),
                  height: setWidth(300),
                  path: state.goodsList[index]['image_default_id'] ?? '',
                  scale: BoxFit.fill,
                ),
                Positioned(
                  left: setWidth(90),
                  top: setWidth(90),
                  child: soldOutBool
                      ? Container(
                          width: setWidth(120),
                          height: setWidth(120),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            color: Color(0xffbbbbbb).withOpacity(0.7),
                            borderRadius: BorderRadius.circular(setWidth(60)),
                          ),
                          child: Text(
                            '售罄',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 15,
                            ),
                          ),
                        )
                      : SizedBox(),
                ),
              ],
            ),
            Padding(
              padding: EdgeInsets.only(
                top: setWidth(16),
                bottom: setWidth(4),
              ),
              child: Text(
                state.goodsList[index]['title'],
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: Color(0xff222222),
                  fontSize: 14,
                ),
              ),
            ),
            Text(
              state.goodsList[index]['sub_title'],
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                color: Color(0xff999999),
                fontSize: 12,
              ),
            ),
            SizedBox(
              height: setWidth(4),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text.rich(
                        TextSpan(
                          children: [
                            TextSpan(
                              text: tiShi + '¥',
                              style: TextStyle(
                                color: Color(0xffEA5504),
                                fontSize: 10,
                              ),
                            ),
                            TextSpan(
                              text: parsePrice(priceStr),
                              style: TextStyle(
                                color: Color(0xffEA5504),
                                fontSize: 16,
                              ),
                            ),
                            WidgetSpan(
                              child: SizedBox(width: 3),
                            ),

                          ],
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                      Text(
                        oldBool ? '¥${parsePrice(oldPriceStr)}' : '',
                        style: TextStyle(
                          color: Color(0xff999999),
                          fontSize: 11,
                          decoration: TextDecoration.lineThrough,
                        ),
                      ),
                    ],
                  ),
                ),
               if( state.goodsList[index]['fresh_type']!=8)  InkWell(
                  onTap: () {
                    print('购物车点击事件！！！');
                    if (!soldOutBool) {
                      // String ecShopNumId =
                      //     SpUtil.getInt('storeShopNum')?.toString();
                      String ecShopNumId =
                          state.goodsList[index]['shop_num_id']?.toString() ??
                              SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'];
                      String itemNumId = state.goodsList[index]
                              ['default_item_num_id']
                          ?.toString();
                      String styleNumId =
                          state.goodsList[index]['style_num_id']?.toString();
                      String ecStyleNumId =
                          state.goodsList[index]['ec_style_num_id']?.toString();
                      logic.requestAddGoods(
                          '$ecShopNumId', itemNumId, styleNumId, ecStyleNumId);
                    }
                  },
                  child: Container(
                    padding: EdgeInsets.only(
                      left: setWidth(10),
                      top: setWidth(4),
                      bottom: setWidth(4),
                    ),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(setWidth(25)),
                      child: Image.asset(
                        'assets/images/shoppingCart_image.png',
                        width: setWidth(50),
                        height: setWidth(50),
                        color: !soldOutBool
                            ? Color(0xffEA5504)
                            : Color(0xffcccccc),
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 单排 item
  Widget _singleRowItemWidget({
    int index,
  }) {
    String priceStr = '', oldPriceStr = '', tiShi = '';
    bool oldBool = false;
    if (state.goodsList[index]['is_seckill'] == 1) {
      // 秒杀商品
      priceStr = state.goodsList[index]['price'].toString();
      oldBool = state.goodsList[index]['mkt_price'] >
          state.goodsList[index]['price']; // 显示旧价格
      oldPriceStr = state.goodsList[index]['mkt_price'].toString();
    } else if (state.goodsList[index]['is_pre_sale'] == 1) {
      priceStr = state.goodsList[index]['price'].toString();
      oldBool = state.goodsList[index]['mkt_price'] >
          state.goodsList[index]['price']; // 显示旧价格
      oldPriceStr = state.goodsList[index]['mkt_price'].toString();
    } else {
      if (state.goodsList[index]['expect_price'] > 0) {
        priceStr = '${state.goodsList[index]['expect_price'].toString()}';
        tiShi = '折后';
        oldBool = state.goodsList[index]['mkt_price'] >
            state.goodsList[index]['expect_price']; // 显示旧价格
        oldPriceStr = state.goodsList[index]['mkt_price'].toString();
      } else {
        priceStr = state.goodsList[index]['price'].toString();
        oldBool = state.goodsList[index]['mkt_price'] >
            state.goodsList[index]['price']; // 显示旧价格
        oldPriceStr = state.goodsList[index]['mkt_price'].toString();
      }
    }
    bool soldOutBool = state.goodsList[index]['style_store'] <= 0;
    return InkWell(
      onTap: () {
        String itemNumId =
            state.goodsList[index]['default_item_num_id']?.toString() ?? '';
        String styleNumId =
            state.goodsList[index]['style_num_id']?.toString() ?? '';
        String shopId = state.goodsList[index]['shop_num_id']?.toString() ?? '';
        String cat1Id = state.goodsList[index]['cat1_id']?.toString() ?? '';
        Get.toNamed(RouteConfig.goodsDetail, arguments: {
          'itemNumId': itemNumId,
          'styleNumId': styleNumId,
          'shopId': shopId,
          'cat1Id': cat1Id,
          'typeIndex': state.goodsList[index]['is_pre_sale'],
        });
      },
      child: Container(
        color: Colors.white,
        child: Column(
          children: [
            Container(
              padding: EdgeInsets.only(
                left: setWidth(30),
                top: setWidth(24),
                right: setWidth(30),
              ),
              child: Row(
                children: [
                  // Image.network(
                  //   state.goodsList[index]['image_default_id'],
                  //   width: setWidth(200),
                  //   height: setWidth(200),
                  //   fit: BoxFit.cover,
                  // ),
                  Stack(
                    children: [
                      CachedImage(
                        width: setWidth(200),
                        height: setWidth(200),
                        path: state.goodsList[index]['image_default_id'] ?? '',
                        scale: BoxFit.fill,
                      ),
                      Positioned(
                        left: setWidth(40),
                        top: setWidth(40),
                        child: soldOutBool
                            ? Container(
                                width: setWidth(120),
                                height: setWidth(120),
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                  color: Color(0xffbbbbbb).withOpacity(0.7),
                                  borderRadius:
                                      BorderRadius.circular(setWidth(60)),
                                ),
                                child: Text(
                                  '售罄',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 15,
                                  ),
                                ),
                              )
                            : SizedBox(),
                      ),
                    ],
                  ),

                  SizedBox(
                    width: setWidth(30),
                  ),
                  Expanded(
                    child: Container(
                      height: setWidth(204),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                state.goodsList[index]['sub_title'],
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                  color: Color(0xff222222),
                                  fontSize: 14,
                                ),
                              ),

                            ],
                          ),
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Expanded(
                                child: Container(
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    mainAxisAlignment: MainAxisAlignment.end,
                                    children: [
                                      Text.rich(
                                        TextSpan(
                                          children: [
                                            TextSpan(
                                              text: tiShi + '¥',
                                              style: TextStyle(
                                                color: Color(0xffEA5504),
                                                fontSize: 10,
                                              ),
                                            ),
                                            TextSpan(
                                              text: parsePrice(priceStr),
                                              style: TextStyle(
                                                color: Color(0xffEA5504),
                                                fontSize: 16,
                                              ),
                                            ),
                                            WidgetSpan(
                                              child: SizedBox(width: 3),
                                            ),
                                            // TextSpan(
                                            //   text: state.goodsList[index]['commission_amount'] > 0 ? '赚${state.goodsList[index]['commission_amount']}' : '',
                                            //   style: TextStyle(
                                            //     color: Color(0xffdd2f3e),
                                            //     fontSize: 10,
                                            //   ),
                                            // ),
                                          ],
                                        ),
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                      Text(
                                        oldBool
                                            ? '¥${parsePrice(oldPriceStr)}'
                                            : '',
                                        style: TextStyle(
                                          color: Color(0xff999999),
                                          fontSize: 11,
                                          decoration:
                                              TextDecoration.lineThrough,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                              if( state.goodsList[index]['fresh_type']!=8)    InkWell(
                                onTap: () {
                                  print('购物车 点击事件事件  单排   ！！！');
                                  if (!soldOutBool) {
                                    // String ecShopNumId =
                                    //     SpUtil.getInt('storeShopNum')
                                    //         ?.toString();
                                    String ecShopNumId = state.goodsList[index]
                                                ['shop_num_id']
                                            ?.toString() ??
                                        SpUtil.getObject(
                                                Config.GET_SHOP_INFO)['shop_id']
                                            ?.toString();
                                    String itemNumId = state.goodsList[index]
                                            ['default_item_num_id']
                                        ?.toString();
                                    String styleNumId = state.goodsList[index]
                                            ['style_num_id']
                                        ?.toString();
                                    String ecStyleNumId = state.goodsList[index]
                                            ['ec_style_num_id']
                                        ?.toString();
                                    logic.requestAddGoods(ecShopNumId,
                                        itemNumId, styleNumId, ecStyleNumId);
                                  }
                                },
                                child: Container(
                                  padding: EdgeInsets.only(
                                    left: setWidth(20),
                                    top: setWidth(4),
                                    bottom: setWidth(4),
                                  ),
                                  child: ClipOval(
                                    child: Image.asset(
                                      'assets/images/shoppingCart_image.png',
                                      width: setWidth(56),
                                      height: setWidth(56),
                                      color: !soldOutBool
                                          ? Color(0xffEA5504)
                                          : Color(0xffcccccc),
                                      fit: BoxFit.cover,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(
              height: setWidth(14),
            ),
            Divider(
              height: setWidth(1),
              indent: setWidth(260),
              color: Color(0xffefefef),
              endIndent: 0,
            ),
          ],
        ),
      ),
    );
  }
}
